package cn.e2win.biz.comm;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javassist.expr.NewArray;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.e2win.base.entity.SysAttach;
import cn.e2win.base.json.vo.Pager;
import cn.e2win.biz.annotation.PageParam;
import cn.e2win.biz.base.BaseController;
import cn.e2win.biz.base.BaseService;
import cn.e2win.biz.dbo.DsRelation;
import cn.e2win.biz.sys.Dict;
import cn.e2win.biz.sys.SimpleMap;
import cn.e2win.biz.sys.SysAttachService;
import cn.e2win.biz.util.PropertiesUtil;


@Controller
@Scope("request")
@RequestMapping("/comm")
public class CommController extends BaseController{

	@Autowired
	private SysAttachService sysAttachService;


	@Override
	public BaseService initService() {
		return sysAttachService;
	}  



	/**
	 * 文件上传通用方法
	 * @param name
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)  
    public ModelAndView handleFormUpload(@RequestParam("file") MultipartFile file,
    		@RequestParam("attachInput") String attachInput,
    		@RequestParam("msgSpan") String msgSpan,
    		@RequestParam("submitBtn") String submitBtn,
    		HttpServletRequest request) { 

		ModelAndView mv = new ModelAndView();
        //MultipartFile是对当前上传的文件的封装，当要同时上传多个文件时，可以给定多个MultipartFile参数  
        mv.addObject("attachInput", attachInput);
        mv.addObject("msgSpan", msgSpan);
        mv.addObject("submitBtn", submitBtn);
        if (!file.isEmpty()) {  
        	InputStream inputStream = null;
        	OutputStream outputStream = null;
        	try {
        		request.setCharacterEncoding("UTF-8");//你的编码格式
        		String fileNameString = file.getOriginalFilename();

    		    
        		//得到后缀名
        		String fileType = fileNameString.substring(fileNameString.indexOf("."));
        		//不能上传文件 exe...
        		if("exe".equalsIgnoreCase(fileType)) {
        			mv.addObject("msg","错误的文件格式！");
        			mv.setViewName("comm/upload_fail");
        			return mv;  
        		}
        		
        		
        		//以时间戳为文件名
        		String time = new java.util.Date().getTime()+"";
        		String path = PropertiesUtil.getProperty(PropertiesUtil.UPLOAD_FILE_PATH);
        		URLEncoder.encode(fileNameString,"UTF-8");
    		    String fileName = new String(fileNameString.getBytes("ISO8859-1"),"UTF-8");
                //save DB
                SysAttach sysAttach = new SysAttach();
                sysAttach.setFileName(fileName);
                sysAttach.setFilePath(path);
                sysAttach.setFileSize(file.getSize());
                sysAttach = (SysAttach)sysAttachService.edit(sysAttach);
                mv.addObject("attachId",sysAttach.getId()+"");

				inputStream = file.getInputStream();
				outputStream = new FileOutputStream(new File(path+"/"+sysAttach.getId()));
				 byte[] buf = new byte[1024]; 
                 int len = -1; 
                 while ((len = inputStream.read(buf)) != -1) { 
                	 outputStream.write(buf, 0, len); 
                 }
			} catch (IOException e) {
				logger.error(e);
				mv.addObject("msg","文件超过最大10M限制");
    			mv.setViewName("comm/upload_fail");
    			return mv;
			}catch (Exception e){
				logger.error(e);
				mv.addObject("msg",e.getMessage());
    			mv.setViewName("comm/upload_fail");
			} finally {
				try {
					outputStream.close();
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	mv.setViewName("comm/upload_suc");
            return mv;  
       } else {
    	    mv.addObject("msg","请选择要上传的文件！");
    	    mv.setViewName("comm/upload_fail");
			return mv;
       }  
    }
	
	
	/**
	 * 文件下载
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("download/{id}")  
	public ResponseEntity<byte[]> download(@PathVariable(ID) Integer id){ 
	    try { 
			SysAttach attach = (SysAttach)sysAttachService.getEntity(SysAttach.class,id);
		    HttpHeaders headers = new HttpHeaders();
		    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
		    headers.setContentDispositionFormData("attachment", attach.getFileName());  
	    
			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(attach.getFilePath()+id)),  
			                                  headers, HttpStatus.CREATED);
		} catch (IOException e) {

		}  
		return null;
	}

	@RequestMapping("getDictList") 
	@ResponseBody
	public List<SimpleMap> getDictList(HttpServletRequest request,
			@PageParam Pager pager, ModelMap modelMap) {
		List<SimpleMap> r = new ArrayList<SimpleMap>();
		try {
			request.setCharacterEncoding("UTF-8");
			String type = new String(request.getParameter("type").getBytes("iso8859-1"),"utf-8");
			r = Dict.getList(type);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return r;
	}

	@RequestMapping(value="getDictOptions", produces="text/html;charset=UTF-8") 
	@ResponseBody
	public String getDictOptions(HttpServletRequest request,HttpServletResponse response,
			@PageParam Pager pager, ModelMap modelMap) {
		String r = "<option value=''>请选择</option>";
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType( "text/xml" );
			response.setCharacterEncoding( "UTF-8" );
			String type = new String(request.getParameter("type").getBytes("iso8859-1"),"utf-8");
			for(SimpleMap map : Dict.getList(type)){
				r= "<option value='" + map.getKEY() + "'>" + map.getVALUE() + "</option>";				
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return r;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    @RequestMapping("/excel")  
    public ModelAndView viewExcel(HttpServletRequest request,  @PageParam Pager pager,
            HttpServletResponse response) {  
        Map model = new HashMap();        
        System.err.println(pager.getSql());
        model.put("list", new ArrayList());         
        return new ModelAndView(new ViewExcel(), model);  
    }  
  
    @RequestMapping("/jxlExcel")  
    public ModelAndView viewJxlExcel(HttpServletRequest request,  
            HttpServletResponse response) {
    	String titles = "一,二,三,四,五";
    	String colums = "AA,BB,CC,DD,EE";
        String [] array1 = null;  
        if(null != colums && colums.indexOf(",") != -1){  
            array1 = colums.split(",");  
        }  
        String [] array2 = null;  
        if(null != titles && titles.indexOf(",") != -1){  
            array2 = titles.split(",");  
        }             
        Map model = new HashMap();  
        // 构造数据  
        List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();  
        for(int i=0; i<10; i++){
        	Map<String, Object> map = new HashMap<String, Object>();
        	map.put("aa", "dfa" + i);
        	map.put("bb", "3234" + i);
        	map.put("cc", "3wer" + i);
        	map.put("dd", "t54rd" + i);
        	map.put("ee", "adr34" + i);
        	users.add(map);
        }

        model.put("list", users);         
        model.put("columns", array1);  
        model.put("titles", array2);          
        return new ModelAndView(new ViewJXLExcel(), model);  
    }  
      
    @RequestMapping("/pdf")  
    public ModelAndView viewPDF(HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  
        Map model = new HashMap();        
        model.put("list", new ArrayList());             
        return new ModelAndView(new ViewPDF(), model);  
    } 
    
    
    
    
    


	

}

